package com.dingxin.ship_together_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingxin.ship_together_api.config.exception.CustomException;
import com.dingxin.ship_together_api.entity.RouteSeat;
import com.dingxin.ship_together_api.entity.RouteSku;
import com.dingxin.ship_together_api.entity.enums.ExceptionEnum;
import com.dingxin.ship_together_api.mapper.RouteSeatMapper;
import com.dingxin.ship_together_api.service.RouteSeatService;
import com.dingxin.ship_together_api.service.RouteSkuService;
import com.dingxin.ship_together_api.service.RouteSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class RouteSeatServiceImpl extends ServiceImpl<RouteSeatMapper, RouteSeat> implements RouteSeatService {

    @Autowired
    private RouteSpuService spuService;
    @Autowired
    private RouteSkuService skuService;


    @Override public boolean checkSeatUsed(Long skuId, List<Long> seatsIdList) {
        QueryWrapper<RouteSku> wrapper = new QueryWrapper<>();
        wrapper.eq(RouteSku.COL_ROUTE_SPU_ID, skuService.getBaseMapper().selectById(skuId).getRouteSpuId());
        List<RouteSku> routeSkuList = skuService.list(wrapper);
        // seatsIdList是否全部包含在routeSkuList中，且routeSku库存大于0,且routeSkuList中seatUsed为false
        List<Long> testSeatIdList = routeSkuList.stream().map(RouteSku::getSeatId).collect(Collectors.toList());
        Optional.ofNullable(testSeatIdList).orElseThrow(() -> new CustomException(ExceptionEnum.SEAT_NOT_FOUND));
        for (Long seatId : seatsIdList) {
            if (!testSeatIdList.contains(seatId)) {
                throw new CustomException(ExceptionEnum.SEAT_NOT_FOUND);
            }
        }
        // 检测库存
        routeSkuList.stream().filter(sku->seatsIdList.contains(sku.getSeatId())).forEach(sku->{
            if (sku.getStock()<=0) {
                throw new CustomException(ExceptionEnum.OUT_OF_STOCK);
            }
        });
        // 返回false未占用
        return false;
    }
}
